package com.example.ttl1.service;

import com.example.ttl1.vo.Orders;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * ClassName:MessageService
 * Package:com.example.ttl1.service
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/8/11-21:30
 * @Version:v1.0
 */
@Service
@Slf4j
public class MessageService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Value("${my.exchangeName}")
    private String exchangeName;

    /**
     * 序列化和反序列化(json格式)
     */
    @Resource
    private ObjectMapper objectMapper;

    public static final String ORDER_ID = "order_12345";

    /**
     * 设置发布者的确认模式
     * 构造方法执行后自动执行
     */
    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(
                //开启生产者的确认模式
                (CorrelationData, ack, cause) -> {
                    if (!ack) {
                        log.error("消息没有到达交换机,原因为：{}", cause);
                        //TODO 重发消息或者记录错误日志
                    }
                }
        );
        rabbitTemplate.setReturnsCallback(
                new RabbitTemplate.ReturnsCallback() {
                    @Override
                    public void returnedMessage(ReturnedMessage returned) {
                        log.error("消息没有从交换机正确的投递(路由)到队列,原因为：{}", returned.getReplyText());
                    }
                }
        );
    }

    public void sendMsg() throws JsonProcessingException {

        //第一条消息
        {
            Orders orders1 = Orders.builder()
                    .orderId(ORDER_ID)
                    .orderName("华为")
                    .orderMoney(new BigDecimal(2365))
                    .orderTime(new Date())
                    .build();
            //序列化(json)
            String strOrders1 = objectMapper.writeValueAsString(orders1);


            MessageProperties messageProperties = new MessageProperties();
            //设置单条消息的持久化
            messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);

            Message message = MessageBuilder.withBody(strOrders1.getBytes()).andProperties(messageProperties).build();

            rabbitTemplate.convertAndSend(exchangeName, "info", message);
        }

        //第二条消息
        {
            Orders orders2 = Orders.builder()
                    .orderId(ORDER_ID)
                    .orderName("华为")
                    .orderMoney(new BigDecimal(2365))
                    .orderTime(new Date())
                    .build();
            String strOrders2 = null;

                strOrders2 = objectMapper.writeValueAsString(orders2);

                MessageProperties messageProperties = new MessageProperties();
                //设置单条消息的持久化
                messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);

                Message message = MessageBuilder.withBody(strOrders2.getBytes()).andProperties(messageProperties).build();

                rabbitTemplate.convertAndSend(exchangeName, "info", message);
        }
        log.info("消息发送完毕,发送时间为:{}",new Date());
    }


}
